package com.kun.kunkunmall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.kun.common.constant.AuthServerConstant;
import com.kun.common.exception.BizCodeEnum;
import com.kun.common.utils.R;
import com.kun.common.vo.MemberRespVo;
import com.kun.kunkunmall.auth.feign.MemberFeignService;
import com.kun.kunkunmall.auth.feign.ThirdPartyFeignService;
import com.kun.kunkunmall.auth.vo.UserLoginVo;
import com.kun.kunkunmall.auth.vo.UserRegisterVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 登陆页面逻辑，若用户已经登录，则再次访问登录页应该跳回首页
     * @return
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object loginUser = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (loginUser == null) {
            // 未登录
            return "login";
        }else {
            return "redirect:http://kunkunmall.com";
        }

    }


    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCOde(@RequestParam("phone") String phone) {
        // 1.解决接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (StringUtils.isNotEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                // 60s内不能再发请求
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        // 2.解决验证码再次校验,存入key-phone，value-code
        String code = UUID.randomUUID().toString().substring(0, 5);
        String subString = code + "_" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, subString, 10, TimeUnit.MINUTES);
        thirdPartyFeignService.sendCode(phone, code);
        return R.ok();
    }

    @PostMapping("/register")
    public String register(@Validated UserRegisterVo vo, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            // 校验出错，转到注册页
            return "redirect:http://auth.kunkunmall.com/register.html";
        }
        // 前置校验没有问题，进行真正注册
        // 1.校验验证码dianzkekda1941
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (StringUtils.isNotEmpty(s)) {
            String redisCode = s.split("_")[0];
            if (redisCode.equals(code)) {
                // 删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                // 验证码校验成功，调用远程服务，进行注册
                R r = memberFeignService.register(vo);
                if (r.getCode() == 0) {
                    // 成功
                    return "redirect:http://auth.kunkunmall.com/login.html";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData("msg", new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.kunkunmall.com/register.html";
                }
            } else {
                // 验证码校验失败
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.kunkunmall.com/register.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.kunkunmall.com/register.html";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo loginVo, RedirectAttributes redirectAttributes, HttpSession session) {

        // 远程登录
        R r = memberFeignService.login(loginVo);
        if (r.getCode() == 0) {
            MemberRespVo memberRespVo = r.getData("data", new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER,memberRespVo);
            return "redirect:http://kunkunmall.com";
        } else {
            Map<String,String> errors = new HashMap<>();
            errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return  "redirect:http://auth.kunkunmall.com/login.html";
        }
    }
}
